'use client';

import { useState, useRef, useEffect } from 'react';
import { List, Avatar, Input, Card, Empty, Button, message, Modal, Form, Popover, Tag, Spin } from 'antd';
import { queryFriendListUsingPost, queryFriendUsingPost, addFriendUsingPost } from '@/api/userRelationshipController';
import styles from './index.module.css';
import { UserAddOutlined, ReloadOutlined } from '@ant-design/icons';
import { ManOutlined, WomanOutlined } from '@ant-design/icons';

const { Search } = Input;

interface FriendData {
  userAccount: string;
  userAvatar: string;
  remarks: string;
}

interface SearchResult {
  userAccount?: string;
  userAvatar?: string;
  userName?: string;
  gender?: string;
}

interface AddFriendForm {
  afriendsNameRemarks: string;
  addFriendsRemarks: string;
}

const genderIcon = (gender?: string) => {
  if (gender === '男') return <ManOutlined style={{ color: '#1890ff', marginRight: 4 }} />;
  if (gender === '女') return <WomanOutlined style={{ color: '#eb2f96', marginRight: 4 }} />;
  return null;
};

function getLvIcon(riceScore?: number) {
  const lv = Math.min(Math.floor((riceScore || 0) / 1000) + 1, 20);
  return <img src={`/assets/lv/lv${lv}.svg`} alt={`lv${lv}`} style={{ width: 24, marginLeft: 4 }} />;
}

export default function FriendList({ friendList }: { friendList: FriendData[] }) {
  const [searchResult, setSearchResult] = useState<SearchResult | null>(null);
  const [loading, setLoading] = useState(false);
  const [addLoading, setAddLoading] = useState(false);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [form] = Form.useForm<AddFriendForm>();
  // 分页相关
  const PAGE_SIZE = 12;
  const [page, setPage] = useState(1);
  const total = friendList.length;
  const pageCount = Math.ceil(total / PAGE_SIZE);
  const pagedList = friendList.slice(0, page * PAGE_SIZE);
  const [friendSearchList, setFriendSearchList] = useState<FriendData[]>([]);
  const [inputValue, setInputValue] = useState('');
  const [inputFocused, setInputFocused] = useState(false);
  const [hoveredUser, setHoveredUser] = useState<string | null>(null);
  const inputRef = useRef<HTMLInputElement>(null);

  // 搜索逻辑：先查好友列表，再查全局用户
  const handleSearch = async (value: string) => {
    if (!value.trim()) {
      setSearchResult(null);
      setFriendSearchList([]);
      return;
    }
    setLoading(true);
    try {
      // 先查好友列表
      const friendListRes = await queryFriendListUsingPost({
        friendsUserAccount: value.trim()
      });
      // 兼容后端返回格式
      const friendListData = friendListRes?.data as FriendData[] || [];
      if (Array.isArray(friendListData) && friendListData.length > 0) {
        setFriendSearchList(friendListData);
        setSearchResult(null);
      } else {
        // 不是好友，再查全局用户
        const response = await queryFriendUsingPost({
          friendsUserAccount: value.trim()
        });
        // 兼容后端返回格式
        const resData = response?.data as any;
        //@ts-ignore
        if (response?.code === 0 && resData && (resData.userAccount || resData.userName)) {
          setSearchResult({
            userAccount: resData.userAccount,
            userAvatar: resData.userAvatar,
            userName: resData.userName,
            gender: resData.gender,
          });
          setFriendSearchList([]);
        } else {
          setSearchResult(null);
          setFriendSearchList([]);
          message.error(resData?.message || '未找到该用户');
        }
      }
    } catch (error: any) {
      setSearchResult(null);
      setFriendSearchList([]);
      message.error(error?.message || '搜索失败');
    } finally {
      setLoading(false);
    }
  };

  const handleAddFriend = async () => {
    try {
      const values = await form.validateFields();
      setAddLoading(true);
      const response = await addFriendUsingPost({
        friendsUserAccount: searchResult?.userAccount,
        afriendsNameRemarks: values.afriendsNameRemarks,
        addFriendsRemarks: values.addFriendsRemarks,
      });
      const res = response.data;
      //@ts-ignore
      if (response.code === 0) {
        message.success('好友请求已发送');
        setIsModalVisible(false);
        setSearchResult(null);
        form.resetFields();
      } else {
        message.error(res?.message || '发送失败');
      }
    } catch (error: any) {
      message.error(error?.message || '请填写备注信息');
    } finally {
      setAddLoading(false);
    }
  };

  // 渲染优先级：搜索到的好友 > 搜索到的非好友 > 默认分页
  return (
    <div className={styles.container}>
      <div className={styles.customSearchBox}>
        <input
          ref={inputRef}
          className={styles.customInput}
          placeholder={inputFocused ? '' : '搜索/添加好友'}
          value={inputValue}
          onChange={e => setInputValue(e.target.value)}
          onKeyDown={e => { if (e.key === 'Enter') handleSearch(inputValue); }}
          disabled={loading}
          onFocus={() => setInputFocused(true)}
          onBlur={() => setInputFocused(false)}
        />
        <button
          className={styles.customSearchBtn}
          onClick={() => handleSearch(inputValue)}
          disabled={loading}
        >
          {loading ? '查询中...' : '搜索好友'}
        </button>
      </div>
      {/* 搜索到的好友（已是好友） */}
      {friendSearchList.length > 0 ? (
        <List
          className={styles.friendList}
          dataSource={friendSearchList}
          renderItem={(item) => {
            return (
              <List.Item
                onMouseEnter={() => setHoveredUser(item.userAccount)}
                onMouseLeave={() => setHoveredUser(null)}
                style={{ cursor: 'pointer' }}
              >
                <FriendPopover 
                  userAccount={item.userAccount} 
                  open={hoveredUser === item.userAccount}
                >
                    <Avatar src={item.userAvatar || "/assets/userAvatar.png"} size={48} />
                  </FriendPopover>
                <List.Item.Meta
                  avatar={null}
                title={item.remarks || item.userAccount}
                description={item.userAccount}
              />
            </List.Item>
            );
          }}
          locale={{
            emptyText: <Empty description="暂无好友" />
          }}
        />
      ) : searchResult ? (
        // 搜索到的非好友
        <Card className={styles.searchResult}>
          <List.Item
            actions={[
              <Button
                key="add"
                type="primary"
                icon={<UserAddOutlined />}
                loading={addLoading}
                style={{ backgroundColor: '#52C41A', borderColor: '#52C41A' }}
                onClick={() => setIsModalVisible(true)}
              >
                添加好友
              </Button>
            ]}
          >
            <FriendPopover 
              userAccount={searchResult.userAccount || ''} 
              open={hoveredUser === searchResult.userAccount}
            >
              <Avatar src={searchResult.userAvatar || "/assets/userAvatar.png"} size={48} />
            </FriendPopover>
            <List.Item.Meta
              avatar={null}
              title={searchResult.userName || searchResult.userAccount}
              description={`${searchResult.gender || ''} · ${searchResult.userAccount}`}
            />
          </List.Item>
        </Card>
      ) : (
        // 默认分页展示
        <>
          <List
            className={styles.friendList}
            dataSource={pagedList}
            renderItem={(item) => {
              return (
                <List.Item
                  onMouseEnter={() => setHoveredUser(item.userAccount)}
                  onMouseLeave={() => setHoveredUser(null)}
                  style={{ cursor: 'pointer' }}
                >
                  <FriendPopover 
                    userAccount={item.userAccount} 
                    open={hoveredUser === item.userAccount}
                  >
                      <Avatar src={item.userAvatar || "/assets/userAvatar.png"} size={48} />
                    </FriendPopover>
                  <List.Item.Meta
                    avatar={null}
                  title={item.remarks || item.userAccount}
                  description={item.userAccount}
                />
              </List.Item>
              );
            }}
            locale={{
              emptyText: <Empty description="暂无好友" />
            }}
          />
          {/* 分页查看更多按钮 */}
          {page < pageCount && (
            <div style={{ display: 'flex', justifyContent: 'center', margin: '24px 0 0 0' }}>
              <Button
                type="text"
                icon={<ReloadOutlined />}
                style={{ color: '#1890FF', fontWeight: 500, fontSize: 16, background: 'none', boxShadow: 'none', border: 'none', display: 'flex', alignItems: 'center' }}
                onClick={() => setPage(page + 1)}
              >
                查看更多好友
              </Button>
            </div>
          )}
        </>
      )}

      <Modal
        title="申请添加朋友"
        open={isModalVisible}
        onCancel={() => {
          setIsModalVisible(false);
          form.resetFields();
        }}
        footer={[
          <Button 
            key="submit" 
            type="primary" 
            loading={addLoading}
            onClick={handleAddFriend}
            style={{ backgroundColor: '#52C41A', borderColor: '#52C41A' }}
          >
            发送
          </Button>
        ]}
      >
        <Form
          form={form}
          layout="vertical"
        >
          <Form.Item
            name="addFriendsRemarks"
            label="发送添加朋友申请"
            rules={[{ required: true, message: '请输入申请信息'}]}
          >
            <Input.TextArea placeholder="我是" />
          </Form.Item>
          <Form.Item
            name="afriendsNameRemarks"
            label="设置备注名"
            rules={[{ required: true, message: '请输入备注名' }]}
          >
            <Input placeholder="请输入备注名" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}

export function FriendPopover({ userAccount, children, open }: { userAccount: string, children: React.ReactNode, open?: boolean }) {
  const [visible, setVisible] = useState(false);
  const [info, setInfo] = useState<any>(null);
  const [loading, setLoading] = useState(false);

  const fetchInfo = async () => {
    setLoading(true);
    try {
      const res = await queryFriendUsingPost({ friendsUserAccount: userAccount });
      if (res.data) setInfo(res.data);
    } finally {
      setLoading(false);
    }
  };

  // 新增：监听open为true时自动拉取数据
  useEffect(() => {
    if ((open !== undefined ? open : visible) && !info && !loading) {
      fetchInfo();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open, visible, userAccount]);

  const content = info ? (
    <div style={{ maxWidth: 220 }}>
      <div style={{ display: 'flex', alignItems: 'center', marginBottom: 8 }}>
        <Avatar src={info.userAvatar} size={48} />
        <div style={{ marginLeft: 12 }}>
          <div style={{ fontWeight: 600, fontSize: 16 }}>{info.userName}</div>
          <div style={{ display: 'flex', alignItems: 'center', marginTop: 2 }}>
            {genderIcon(info.gender)}
            {getLvIcon(info.riceScore)}
          </div>
        </div>
      </div>
      <div style={{ color: '#888', fontSize: 13, marginBottom: 8 }}>
        {info.userProfile || '这个人很懒，还没有简介~'}
      </div>
      <div style={{ marginBottom: 8 }}>
        {info.area && <Tag color="blue">{info.area}</Tag>}
        {info.direction && <Tag color="green">{info.direction}</Tag>}
        <Tag color="default">{info.createTime?.slice(0, 10)}</Tag>
      </div>
    </div>
  ) : <Spin />;

  return (
    <Popover
      content={content}
      trigger="hover"
      onOpenChange={v => {
        setVisible(v);
      }}
      open={open !== undefined ? open : visible}
    >
      {children}
    </Popover>
  );
} 